package com.leetcode.sort;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @author Dennis Li
 * @date 2020/7/24 22:37
 */
public class FrequencySort_451 {

    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : s.toCharArray())
            map.put(c, map.getOrDefault(c, 0) + 1);
        PriorityQueue<Map.Entry<Character, Integer>> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
        map.entrySet().forEach(queue::offer);
        StringBuilder sb = new StringBuilder();
        while (!queue.isEmpty()) {
            Map.Entry<Character, Integer> entry = queue.poll();
            char ch = entry.getKey();
            int len = entry.getValue();
            for (int i = 0; i < len; i++)
                sb.append(ch);
        }
        return sb.toString();
    }

}
